package com.example.mountain;

import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class light extends Fragment implements View.OnClickListener {
	Camera camera = null;
	Context context = null;
	boolean isOn = false;
	Button toggleBT = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_flash, viewGroup,
				false);
		context = rootView.getContext();
		toggleBT = (Button) rootView.findViewById(R.id.toggleBT);
		toggleBT.setOnClickListener(this);
		if (!isSupportedFlash()) {
			Toast.makeText(context, "Flash 미지원", Toast.LENGTH_SHORT).show();
		} else {
			cameraRelease();
			try {
				camera = Camera.open();
			} catch (RuntimeException e) {
				camera = null;
				Toast.makeText(context, "CAMERA 자원에 접근불가", Toast.LENGTH_SHORT)
						.show();
			}
		}
		return rootView;
	}

	@Override
	public void onDestroyView() {
		cameraRelease();
		super.onDestroyView();
	}

	void cameraRelease() {
		if (camera != null) {
			camera.release();
			camera = null;
		}
	}

	boolean isSupportedFlash() {
		PackageManager pm = context.getPackageManager();
		return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
				&& pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
	}

	@Override
	public void onClick(View view) {
		if (camera == null) {
			Toast.makeText(context, "Flash 미지원", Toast.LENGTH_SHORT).show();
		} else {
			isOn = !isOn;
			Parameters params = camera.getParameters();
			if (isOn) {
				params.setFlashMode(Parameters.FLASH_MODE_TORCH);
				toggleBT.setText("ON");
				toggleBT.setBackgroundResource(R.drawable.btnon);

			} else {
				params.setFlashMode(Parameters.FLASH_MODE_OFF);
				toggleBT.setText("OFF");
				toggleBT.setBackgroundResource(R.drawable.btnoff);
			}
			camera.setParameters(params);
			camera.startPreview();
		}
	}
}
